package com.leyou.user.web;

import com.leyou.auth.constant.JwtConstants;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.UserContext;
import com.leyou.user.entity.User;
import com.leyou.user.service.UserService;
import com.leyou.user.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;

@RestController
@RequestMapping("/info")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 解析当前用户信息
     * @param token 用户的token
     * @return
     */
    @GetMapping("/me")
        public ResponseEntity<UserDetail> checkLogin(@CookieValue(JwtConstants.COOKIE_NAME)String token) {
            return ResponseEntity.ok(UserContext.getUser());
    }

    /**
     * 根据用户名和密码查询
     * @param username 用户名
     * @param password 密码
     * @return UserDTO
     */
    @GetMapping
    public ResponseEntity<UserDTO> queryUserByNameAndPass(
            @RequestParam("username")String username,
            @RequestParam("password")String password) {
        return ResponseEntity.ok(userService.queryUserByNameAndPass(username, password));
    }

    /**
     * 用户注册
     * @param user 用户信息
     * @param code 验证码
     */
    @PostMapping
    public ResponseEntity<Void> userRegister(
            @Valid User user,
            @RequestParam("code")String code ) {
        userService.userRegister(user, code);
        return ResponseEntity.ok().build();
    }

    /**
     * 发送短信验证码
     * @param phone 手机号
     */
    @PostMapping("/code")
    public ResponseEntity<Void> sendVerifyCode(@RequestParam("phone") String phone) {
        userService.sendVerifyCode(phone);
        return ResponseEntity.ok().build();
    }

    /**
     * 判断信息是否存在
     *
     * @param data 要校验的数据
     * @param type 数据的类型
     * @return 是否存在
     */
    @GetMapping("/exists/{data}/{type}")
    public ResponseEntity<Boolean> checkExists(
            @PathVariable("data") String data,
            @PathVariable("type") Integer type
    ) {
        return ResponseEntity.ok(userService.checkExists(data, type));
    }
}
